﻿<?php
	include('connect_db.php');
	session_start();
  
	// Connect to the database
	try 
	{
		$conn = getDB();
	}
	catch (Exception $e) {
		echo "Error: " . $e->getMessage();
	}
  
	 /*if logged in, redirect to homepage */
	if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true)
	{
		header('Location: index.php');
		exit();
	}
	
    if (!isset($_POST['reg_email']) || !isset($_POST['reg_password']) || !isset($_POST['reg_password_confirm']) || empty($_POST['reg_email']) || empty($_POST['reg_password']) || empty($_POST['reg_password_confirm'])) {
      $msg = "Please fill in all form fields.";
    }
    else if ($_POST['reg_password'] !== $_POST['reg_password_confirm']) {
      $msg = "Passwords must match.";
    }
    else {
		$user_stmt = $conn->prepare('SELECT * FROM users WHERE username=:username');
		$user_stmt->execute(array(':username' => $_POST['reg_email']));
		$res = $user_stmt->fetch();
		if (!$res) {
			// Generate random salt
			$salt = sha1(uniqid(mt_rand(), true));

			// Apply salt before hashing
			$salted = sha1($salt . $_POST['reg_password']);

			// Store the salt with the password, so we can apply it again and check the result
			$stmt = $conn->prepare("INSERT INTO users (username, password, salt) VALUES (:username, :password, :salt)");
			$stmt->execute(array(':username' => $_POST['reg_email'], ':password' => $salted, ':salt' => $salt));
			$msg = "Account created.";
			
		}
		else {
			$msg = "Cannot create account with duplicate username.";
		}	
    }
  //} 
?>

<?php include('templates/landing/header.php'); ?>

<div id="body">
	<div class="content registration">
		<h1>User Registration</h1>
		<?php 
			if (isset($msg)) 
			{
				echo "<p>$msg</p>"; 
				echo "<form method='post' action='login.php' >";
					echo	"<input type='submit' name='login-secured' value='Go to login page' />";
				echo "</form>";
			}
		?>
	</div>
</div>
<?php include('templates/landing/footer.php'); ?>
